package Thread;
import java.util.concurrent.locks.ReentrantLock;
/**死锁情况3的解决办法2：使用 ReentrantLock 的 tryLock 方法可以尝试获取锁，如果获取不到则可以选择放弃或重试*/
public class demo20_2 {
    public static void main(String[] args) {
        int n = 5; // 线程数量
        int m = 5; // 锁的数量

        ReentrantLock[] locks = new ReentrantLock[m];
        for (int i = 0; i < m; i++) {
            locks[i] = new ReentrantLock();
        }

        for (int i = 0; i < n; i++) {
            final int threadIndex = i;
            Thread t = new Thread(() -> {
                for (int j = 0; j < m; j++) {
                    int lockIndex = (threadIndex + j) % m; // 每个线程以不同的顺序获取锁
                    boolean locked = false;
                    while (!locked) {
                        locked = locks[lockIndex].tryLock();
                        if (locked) {
                            try {
                                System.out.println("线程 " + threadIndex + " 获取锁序号 " + lockIndex);
                                try {
                                    Thread.sleep(1000); // 模拟耗时操作
                                } catch (InterruptedException e) {
                                    throw new RuntimeException(e);
                                }
                            } finally {
                                locks[lockIndex].unlock();
                            }
                        } else {
                            try {
                                Thread.sleep(100); // 重试间隔
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            });
            t.start();
        }
    }
}
